﻿using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace Learning
{
    public class MiscRenderPass1 : ScriptableRenderPass
    {
        public MiscSetting setting;

        // private int _renderTargetId;
        // private RenderTargetIdentifier _renderTargetIdentifier;

        private RTHandle _rtHandle;
        
        public MiscRenderPass1()
        {
            // // 直接关联到Shader属性的做法
            // _renderTargetId = Shader.PropertyToID("_TestTex");
            // // 有new所以不要写到OnCameraSetup和Configure中，会引起奔溃
            // _renderTargetIdentifier = new RenderTargetIdentifier(_renderTargetId);
        }
        
        public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
        {
        }

        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
        {
            // cmd.GetTemporaryRT(_renderTargetId, cameraTextureDescriptor);
            // ConfigureTarget(_renderTargetIdentifier);
            // ConfigureClear(ClearFlag.All, Color.clear);
            
            // 官方推荐的方法，可以写到OnCameraSetup和Configure中，在锁屏等情况丢失贴图后还可以重新创建
            var descriptor = new RenderTextureDescriptor(2560, 1440, GraphicsFormat.B8G8R8A8_UNorm, GraphicsFormat.None);
            RenderingUtils.ReAllocateIfNeeded(ref _rtHandle, descriptor, FilterMode.Point, TextureWrapMode.Clamp, name: "_rtHandle");
            // 通过设置全局参数的方式传递
            cmd.SetGlobalTexture("_Test2Tex", _rtHandle);
            ConfigureTarget(_rtHandle);
            ConfigureClear(ClearFlag.All, Color.clear);
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (setting.material_1 == null)
            {
                return;
            }

            CommandBuffer cmd = CommandBufferPool.Get("MiscRenderPass1");

            // 渲染 RenderTargetIdentifier 的方式
            // RenderTargetIdentifier cameraColorTexture = renderingData.cameraData.renderer.cameraColorTarget;
            // Blit(cmd, cameraColorTexture, _renderTargetIdentifier, setting.material_1);

            // 渲染 RTHandle 的方式
            var colorHandle = renderingData.cameraData.renderer.cameraColorTargetHandle;
            cmd.Blit(colorHandle, _rtHandle.nameID, setting.material_1);
            
            if (setting.rt != null) {
                cmd.Blit(_rtHandle.rt, setting.rt);
            }

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();
            CommandBufferPool.Release(cmd);
        }

        public override void OnCameraCleanup(CommandBuffer cmd)
        {
            // cmd.ReleaseTemporaryRT(_renderTargetId);
            
            RTHandles.Release(_rtHandle);
        }
    }
}
